/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package elaborate.tool.messenger.yahoo;

import com.fasterxml.jackson.databind.ObjectMapper;
import elaborate.tool.messenger.Contact;
import elaborate.tool.messenger.ContactListener;
import elaborate.tool.messenger.MessageListener;
import elaborate.tool.messenger.MessengerConnection;
import elaborate.tool.messenger.MessengerSender;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

/**
 *
 * @author lendle
 */
public class YahooMessengerConnection implements MessengerConnection {

    private String oauth_consumer_key = "dj0yJmk9MDBQNUhLazNmZXNBJmQ9WVdrOU1YQkhVV2h2TjJrbWNHbzlNVEk0TlRBM05EYzJNZy0tJnM9Y29uc3VtZXJzZWNyZXQmeD03Ng--";
    private String consumer_secret = "583e9113b3f1cbe6d11a98de4e8f144f1be5dfcf";
    private String oauth_token;
    private String oauthSecret;
    private String sessionId;
    private String sender;
    private MessageReceiverThread messageReceiverThread = null;
    private YahooContactsLoader contactsLoader=null;
    private HttpUtil httpUtil=null;

    public YahooMessengerConnection(String oauth_consumer_key, String consumer_secret) {
        this.oauth_consumer_key = oauth_consumer_key;
        this.consumer_secret = consumer_secret;
    }

    public YahooMessengerConnection() {
    }

    @Override
    public void connect(String username, String password) throws Exception {
        this.sender = username;
        URL url = new URL("https://login.yahoo.com/WSLogin/V1/get_auth_token?&login=" + username + "&passwd=" + password + "&oauth_consumer_key=" + this.oauth_consumer_key);
        //System.out.println("url="+url);
        //LogFactory.getLog(this.getClass()).error("login url="+url);
        java.util.logging.Logger.getLogger(YahooMessengerConnection.class.getName()).info("login url=" + url);
        BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream()));
        String str = input.readLine();
        String token = null;
        if (str != null) {
            int index = str.indexOf("=");
            token = str.substring(index + 1);
        }
        input.close();

        long timestamp = ((long) (System.currentTimeMillis() / 1000));
        String getTokenURL = "https://api.login.yahoo.com/oauth/v2/get_token?oauth_consumer_key=" + this.oauth_consumer_key + "&"
                + "oauth_signature_method=PLAINTEXT"
                + "&oauth_nonce=24829.2331&"
                + "oauth_timestamp=" + timestamp + "&"
                + "oauth_signature=" + consumer_secret + "%26&"
                + "oauth_version=1.0&"
                + "oauth_token=" + token + "&"
                + "realm=yahooapis.com&"
                + "oauth_callback=oob";
        url = new URL(getTokenURL);
        input = new BufferedReader(new InputStreamReader(url.openStream()));
        str = input.readLine();
        
        if (str != null) {
            int index = str.indexOf("=");
            int index1 = str.indexOf("&", index + 1);
            int index2 = str.indexOf("=", index1 + 1);
            int index3 = str.indexOf("&", index2 + 1);
            this.oauth_token = str.substring(index + 1, index1);
            this.oauthSecret = str.substring(index2 + 1, index3);
        }
        input.close();
        
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpost = new HttpPost("http://developer.messenger.yahooapis.com/v1/session?fieldsBuddyList=%2Bgroups&fieldsBuddyList=%2Baddressbook");
        httpost.setHeader("Content-Type", "application/json;charset=utf-8");
        String oauthCredential = getOauthCredential();
        httpost.setHeader("Authorization", oauthCredential);

        StringEntity entity = new StringEntity("{}");
        httpost.setEntity(entity);
        HttpResponse response = httpClient.execute(httpost);
        String responseString = EntityUtils.toString(response.getEntity());
        //System.out.println(responseString);
        ObjectMapper mapper = new ObjectMapper();
        Map map = mapper.readValue(responseString, Map.class);
        this.sessionId = (String) map.get("sessionId");
        
        //initialize httputil
        this.httpUtil=new HttpUtil(oauth_consumer_key, consumer_secret, oauth_token, oauthSecret, sessionId, username);
        
        messageReceiverThread = new MessageReceiverThread(oauth_consumer_key, consumer_secret, oauth_token, oauthSecret, sessionId, username);
        messageReceiverThread.start();
        
        contactsLoader = new YahooContactsLoader(oauth_consumer_key, consumer_secret, oauth_token, oauthSecret, sessionId);
        Thread.sleep(1000);
        //System.out.println(getContacts().size());
    }

    private String getOauthCredential() {
        long timestamp = ((long) (System.currentTimeMillis() / 1000));
        String oauthCredential = "OAuth realm=\"yahooapis.com\","
                + "oauth_consumer_key=\"" + this.oauth_consumer_key + "\","
                + "oauth_nonce=\"24829.2330\","
                + "oauth_signature_method=\"PLAINTEXT\","
                + "oauth_timestamp=\"" + timestamp + "\","
                + "oauth_token=\"" + this.oauth_token + "\","
                + "oauth_version=\"1.0\","
                + "oauth_signature=\"" + this.consumer_secret + "%26" + this.oauthSecret + "\"";
        return oauthCredential;
    }

    @Override
    public void disconnect() throws Exception {
        httpUtil.doDelete("http://developer.messenger.yahooapis.com/v1/session?sid=" + this.sessionId);
        messageReceiverThread.shutdown();
    }

    @Override
    public MessengerSender getSender() {
        return new YahooMessengerSender(oauth_consumer_key, consumer_secret, oauth_token, oauthSecret, sessionId, sender);
    }

    public void addMessageListener(MessageListener l) {
        this.messageReceiverThread.addMessageListener(l);
    }

    public void removeMessageListener(MessageListener l) {
        this.messageReceiverThread.removeMessageListener(l);
    }

    public List<Contact> getContacts() {
       return this.contactsLoader.getContacts();
    }

    @Override
    public void addContactListener(ContactListener l) {
        this.contactsLoader.addContactListener(l);
    }

    @Override
    public void removeContactListener(ContactListener l) {
        this.contactsLoader.removeContactListener(l);
    }
}
